package com.qupeng.demo.kafka.kafkaapache.consumer;

import com.qupeng.demo.kafka.kafkaapache.producer.Product;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

public class AvroConsumer {
    public KafkaConsumer create() {
        Properties props = new Properties();
        props.put("bootstrap.servers", "localhost:9092");
        props.put("group.id", "test-group");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "io.confluent.kafka.serializers.KafkaAvroDeserializer");
        props.put("schema.registry.url", "localhost:8081");

        return new KafkaConsumer<>(props);
    }

    public void consume() {

        KafkaConsumer<String, Product> consumer = create();
        consumer.subscribe(Arrays.asList("topic1", "topic2"));

        while (true) {
            ConsumerRecords<String, Product> records = consumer.poll(Duration.ofMillis(100));
            // 处理拉取到的消息
            records.forEach(record -> System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value().getName()));
        }
    }
}
